package com.quectel.cms.controller.household;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.business.common.grid.GridMemberBindResourcesBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.core.household.HouseholdConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.dto.HouseholdRelationsDto;
import com.quectel.core.module.household.dto.HouseholdRoomDto;
import com.quectel.core.module.household.dto.custom.CohabitantDto;
import com.quectel.core.module.household.service.HouseholdFamilyService;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.household.service.HouseholdSocialRelationsService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.dto.VillageFloorDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageFloorService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-02 13:11:28
 */
@RestController
@RequestMapping("household")
@Tag(name = "HouseholdController", description = "住户相关api")
public class HouseholdController extends BaseController {

    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private HouseholdRoomService householdRoomService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageFloorService villageFloorService;
    @DubboReference
    private VillageRoomService villageRoomService;
    @DubboReference
    private HouseholdFamilyService householdFamilyService;
    @DubboReference
    private HouseholdSocialRelationsService householdSocialRelationsService;

    @Autowired
    private GridMemberBindResourcesBusiness gridMemberBindResourcesBusiness;

    /**
     * 住户特殊人群的分页列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("specialList")
    @RequirePermissions(values = {"householdSpecialPopulation:list", "gridHouseholdSpecialPopulation:list"})
    @Operation(summary = "住户特殊人群的分页列表")
    public Response<Page<HouseholdDto>> specialList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "网格id") @RequestParam(required = false) Long gridId
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        if (request.isNotBlank(HouseholdConstants.SEARCH_KEYS_STRING)) {
            request.put(HouseholdConstants.TAG_KEYS, ListUtil.toList(request.getString(HouseholdConstants.SEARCH_KEYS_STRING).split(",")));
        }

        List<Long> sourceIds = new ArrayList<>();
        if (gridId != null) {
            sourceIds = gridMemberBindResourcesBusiness.getSourceIdByGridIdAndSourceType(gridId, GridConstant.SourceType.BUILDING.getType());
        }

        request.getParams().put(HouseholdConstants.BUILDING_IDS, sourceIds);

        super.fillAuthorityData(request.getParams());

        //添加重点人员筛选
        request.put(HouseholdConstants.FOCUS_GROUPS_FLAG, SystemConstants.YES);

        int total = householdService.queryTotal(request.getParams());

        List<HouseholdDto> list = null;
        if (total > 0) {
            list = householdService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<HouseholdDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<HouseholdDto>>ok().wrap(page);
    }


    /**
     * 保存住户家庭或者社会关系记录
     */
    @PostMapping("saveOrUpdateRelations")
    @RequirePermissions(values = "household:edit")
    @Operation(summary = "保存住户家庭或者社会关系记录")
    public Response<Object> saveOrUpdateRelations(@RequestBody @Validated HouseholdRelationsDto householdRelationsDto) {
        HouseholdDto householdDto = householdService.selectCacheById(householdRelationsDto.getHouseholdId());
        if (householdDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        householdService.saveOrUpdateRelations(householdRelationsDto);

        return Response.ok();
    }

    /**
     * 列表
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "household:importExcel")
    @Operation(summary = "用Excel导入住户信息")
    @Log(express = "导入人员信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                int successHousehold = 0;
                int successRoom = 0;
                try {
                    //校验楼栋数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);

                    for (Map<Integer, String> map : analysis) {
                        try {

                            String villageName = map.get(5);
                            VillageDto villageDto = villageService.selectByName(SessionHolder.getSysUser().getTenantId(), villageName);
                            if (villageDto == null) {
                                continue;
                            }


                            HouseholdDto householdDto = new HouseholdDto();
                            householdDto.setVillageId(villageDto.getId());
                            householdDto.setName(map.get(0));
                            householdDto.setMobile(map.get(1));
                            householdDto.setCardType(HouseholdConstants.ID_CARD);
                            householdDto.setCardNo(map.get(2));
                            householdDto.setGender(Objects.equals(SystemConstants.MALE_CHINESE, map.get(3)) ? SystemConstants.MALE : SystemConstants.FEMALE);
                            householdDto.setType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.HOUSEHOLD_TYPE, map.get(9), Byte.class));
                            fillSaveCommonData(householdDto);

                            if (StringUtils.isNotBlank(householdDto.getMobile())) {
                                HouseholdDto dbValue = householdService.selectByVillageIdAndMobile(householdDto.getVillageId(), householdDto.getMobile());
                                if (dbValue == null) {
                                    Long id = householdService.save(householdDto);
                                    householdDto.setId(id);
                                } else {
                                    householdDto = dbValue;
                                }
                            } else {
                                householdDto.setMobile(null);
                                Long id = householdService.save(householdDto);
                                householdDto.setId(id);
                            }
                            successHousehold++;


                            String buildingName = map.get(6);
                            VillageBuildingDto villageBuildingDto = villageBuildingService.selectByName(villageDto.getId(), buildingName);
                            if (villageBuildingDto == null) {
                                continue;
                            }

                            VillageFloorDto villageFloorDto = villageFloorService.selectByFloorNo(villageBuildingDto.getId(), Integer.valueOf(map.get(7)));
                            if (villageFloorDto == null) {
                                continue;
                            }
                            //房间不为空
                            VillageRoomDto villageRoomDto = villageRoomService.selectByName(villageFloorDto.getId(), map.get(8));
                            if (villageRoomDto == null) {
                                continue;
                            }


                            HouseholdRoomDto householdRoomDto = householdRoomService.selectByHouseholdIdAndRoomId(householdDto.getId(), villageRoomDto.getId());
                            if (householdRoomDto == null) {
                                householdRoomDto = new HouseholdRoomDto();
                                householdRoomDto.setHouseholdId(householdDto.getId());
                                householdRoomDto.setVillageId(villageRoomDto.getVillageId());
                                householdRoomDto.setRoomId(villageRoomDto.getId());
                                householdRoomDto.setIdentityCategory(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.HOUSEHOLD_IDENTITY_CATEGORY, map.get(9), Byte.class));
                                householdRoomService.save(householdRoomDto);
                            }
                            successRoom++;

                        } catch (Exception e) {
                            logger.error("解析某个人员信息出错", e);
                            continue;
                        }
                    }
                    return Response.customize(Response.getSUCCESS_CODE(), "导入人员数:" + successHousehold + " 导入房间关系数:" + successRoom);
                } catch (Exception e) {
                    logger.error("解析楼栋信息出错");
                }
            }
        }
        return Response.error("导入数据出错");
    }

//    /**
//     * 列表
//     */
//    @GetMapping("downloadTemplate")
//    @RequirePermissions(values = "household:importExcel")
//    @Log(value = "下载模板")
//    public void downloadTemplate(@RequestParam Long buildingId,
//                                 @RequestParam String templateUrl,
//                                 HttpServletResponse hresp) {
//        VillageBuildingDto villageBuildingDto = villageBuildingService.selectById(buildingId);
//        if (villageBuildingDto == null) {
//            throw new CheckErrorException("非法操作");
//        }
//
//        File tempExcel = MyFileUtils.downloadToTempDir(templateUrl, false);
//
//        ExcelWriter writer = ExcelUtil.getWriter(tempExcel, "住户信息");
//        writer.writeCellValue(5, 1, String.valueOf(villageBuildingDto.getId()));
//        writer.writeCellValue(6, 1, villageBuildingDto.getName());
//        writer.flush();
//        writer.close();
//        ServletUtils.write(hresp, tempExcel, "住户信息导入模板.xls");
//    }

    /**
     * 导出住户信息为Excel文件
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "household:exportExcel")
    @Log(express = "导出住户信息为Excel文件")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<HouseholdDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<HouseholdDto> list = householdService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"小区编码", "小区名称", "姓名", "手机号", "性别", "人脸照片", "住户类型", "证件类型", "证件号码", "创建时间"};

        List<String[]> dataList = new ArrayList<>();
        for (HouseholdDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageDto() != null ? data.getVillageDto().getCode() : null;
            item[1] = data.getVillageDto() != null ? data.getVillageDto().getName() : null;
            item[2] = DesensitizedUtil.chineseName(data.getName());
            item[3] = DesensitizedUtil.mobilePhone(data.getMobile());
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.GENDER, data.getGender() + "");
            item[5] = data.getFaceImg();
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.HOUSEHOLD_TYPE, data.getType() + "");
            item[7] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CARD_TYPE, data.getCardType() + "");
            item[8] = DesensitizedUtil.idCardNum(data.getCardNo(), 2, 2);
            item[9] = data.getCreateTime() != null ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "住户信息", headers, dataList, "住户信息");
    }

    /**
     * 住户信息分页列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "household:list")
    @Operation(summary = "住户信息分页列表")
    public Response<Page<HouseholdDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        if (request.isNotBlank(HouseholdConstants.SEARCH_KEYS_STRING)) {
            request.put(HouseholdConstants.TAG_KEYS, ListUtil.toList(request.getString(HouseholdConstants.SEARCH_KEYS_STRING).split(",")));
        }
        if (request.isNotBlank(HouseholdConstants.SEARCH_LABEL_STRING)) {
            request.put(HouseholdConstants.LABEL_KEYS, ListUtil.toList(request.getString(HouseholdConstants.SEARCH_LABEL_STRING).split(",")));
        }
        if (request.isNotBlank(HouseholdConstants.SEARCH_RANGE_STRING)) {
            request.put(HouseholdConstants.AGE_RANGE_KEYS, ListUtil.toList(request.getString(HouseholdConstants.SEARCH_RANGE_STRING).split(",")));
        }


        super.fillAuthorityData(request.getParams());
        int total = householdService.queryTotal(request.getParams());

        List<HouseholdDto> list = null;
        if (total > 0) {
            list = householdService.queryList(request.getParams());
            for (HouseholdDto householdDto : list) {
                householdDto.setName(DesensitizedUtil.chineseName(householdDto.getName()));
                householdDto.setMobile(DesensitizedUtil.mobilePhone(householdDto.getMobile()));
                householdDto.setCardNo(DesensitizedUtil.idCardNum(householdDto.getCardNo(), 2, 2));
            }
        } else {
            list = new ArrayList<>();
        }

        Page<HouseholdDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<HouseholdDto>>ok().wrap(page);
    }

    /**
     * 查询住户单条记录
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "household:edit")
    @Operation(summary = "查询住户单条记录")
    public Response<HouseholdDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdDto householdDto = householdService.selectById(id);
        householdDto.setHouseholdRoomDtoList(householdRoomService.selectByHouseholdId(householdDto.getId()));
        //家庭关系
        householdDto.setHouseholdFamilyList(householdFamilyService.queryByHouseholdId(householdDto.getId()));
        //社会关系
        householdDto.setSocialRelationsList(householdSocialRelationsService.queryByHouseholdId(householdDto.getId()));

        return Response.<HouseholdDto>ok().wrap(householdDto);
    }

    /**
     * 查询住户单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = {"household:info", "gridHousehold:info"})
    @Operation(summary = "查询住户单条记录")
    public Response<HouseholdDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdDto householdDto = householdService.selectById(id);
        if (householdDto != null) {
            householdDto.setName(DesensitizedUtil.chineseName(householdDto.getName()));
            householdDto.setMobile(DesensitizedUtil.mobilePhone(householdDto.getMobile()));
            householdDto.setCardNo(DesensitizedUtil.idCardNum(householdDto.getCardNo(), 2, 2));
        }
        householdDto.setHouseholdRoomDtoList(householdRoomService.selectByHouseholdId(householdDto.getId()));
        //家庭关系
        householdDto.setHouseholdFamilyList(householdFamilyService.queryByHouseholdId(householdDto.getId()));
        //社会关系
        householdDto.setSocialRelationsList(householdSocialRelationsService.queryByHouseholdId(householdDto.getId()));

        List<CohabitantDto> cohabitantDtos = householdRoomService.queryCohabitant(householdDto.getId());
        for (CohabitantDto cohabitantDto : cohabitantDtos) {
            cohabitantDto.setName(DesensitizedUtil.chineseName(householdDto.getName()));
            cohabitantDto.setMobile(DesensitizedUtil.mobilePhone(householdDto.getMobile()));
            cohabitantDto.setCardNo(DesensitizedUtil.idCardNum(householdDto.getCardNo(), 2, 2));
        }
        householdDto.setCohabitants(cohabitantDtos);
        return Response.<HouseholdDto>ok().wrap(householdDto);
    }

    /**
     * 保存住户单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "household:edit")
    @Operation(summary = "保存住户单条记录")
    public Response<Object> save(@RequestBody @Validated HouseholdDto householdDto) {


        if (StringUtils.isNotBlank(householdDto.getMobile())) {
            HouseholdDto dbValue = householdService.selectByVillageIdAndMobile(householdDto.getVillageId(), householdDto.getMobile());
            if (dbValue != null) {
                return Response.error("手机号在该小区已存在");
            }
        }
        if (householdDto.getHouseholdRoomDtoList() != null) {
            for (HouseholdRoomDto villageRoomDto : householdDto.getHouseholdRoomDtoList()) {
                VillageRoomDto v = villageRoomService.selectById(villageRoomDto.getRoomId());

                if (!Objects.equals(v.getVillageId(), householdDto.getVillageId())) {
                    //房间所属小区和住户所属小区不一致 这里简单判断一下 如果严格判断需要去检查数据库房间的所属小区
                    return Response.error("房间所属小区和住户所属小区不一致");
                }
                villageRoomDto.setVillageId(v.getVillageId());
            }
        }

        //填充基础数据
        fillSaveCommonData(householdDto);

        householdService.saveOrUpdateHouseholdAndRoom(householdDto);

        return Response.ok();
    }

    /**
     * 修改住户单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "household:edit")
    @Operation(summary = "修改住户单条记录")
    public Response<Object> update(@RequestBody @Validated HouseholdDto householdDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(householdDto.getId()));
        if (householdService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        if (StringUtils.isNotBlank(householdDto.getMobile())) {
            HouseholdDto dbValue = householdService.selectByVillageIdAndMobile(householdDto.getVillageId(), householdDto.getMobile());
            if (dbValue != null && !Objects.equals(dbValue.getId(), householdDto.getId())) {
                return Response.error("手机号在该小区已存在");
            }
        }
        if (householdDto.getHouseholdRoomDtoList() != null) {
            for (HouseholdRoomDto householdRoomDto : householdDto.getHouseholdRoomDtoList()) {
                VillageRoomDto v = villageRoomService.selectById(householdRoomDto.getRoomId());
                if (!Objects.equals(v.getVillageId(), householdDto.getVillageId())) {
                    //房间所属小区和住户所属小区不一致 这里简单判断一下 如果严格判断需要去检查数据库房间的所属小区
                    return Response.error("房间所属小区和住户所属小区不一致");
                }
                householdRoomDto.setVillageId(v.getVillageId());
            }
        }
        if (StringUtils.isNotBlank(householdDto.getTags()) && "{}".equals(householdDto.getTags())) {
            // 改为非特征人员
            householdDto.setControlLevel((byte)0);
        }
        //填充基础数据
        fillEditCommonData(householdDto);

        householdService.saveOrUpdateHouseholdAndRoom(householdDto);

        return Response.ok();
    }

    /**
     * 批量删除住户记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "household:delete")
    @Operation(summary = "批量删除住户记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (householdService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        householdService.deleteBatch(ids);

        return Response.ok();
    }
}
